package utgame.com.contentpriverderdemo;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Button;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import utgame.com.basedemo.Utils;

/**
 * Created by xueal on 2018/1/26.
 */

public class ContentProviderExample {

    private static final Uri SMS_INBOX = Uri.parse("content://sms/");
    private static final String SEP = System.getProperty("line.separator");

    private static final String CALLIN = "来电";
    private static final String CALLOUT = "去电";
    private static final String CAllMISS = "未接";

    private static Map<String, ContactsInfo> mContactMap = new HashMap<>();

    public static class ContactsInfo {

        private String name;
        private String number;
        private String sortKey;
        private int id;


        public ContactsInfo(String name, String number, String sortKey, int id) {
            setName(name);
            setNumber(number);
            setSortKey(sortKey);
            setId(id);
        }

        public String toString(){
            return name + "|" + number + "|";
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }

        public String getSortKey() {
            return sortKey;
        }

        public void setSortKey(String sortKey) {
            this.sortKey = sortKey;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }


    /**
     * 利用系统CallLog获取通话历史记录
     * @param activity
     * @param num  要读取记录的数量
     * @return
     */
    public static void getCallHistoryList(Activity activity, int num) {

        getContacts(activity, false);

        StringBuilder callLogBuilder = new StringBuilder();

        Cursor cs;
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 1000);

        }
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.WRITE_CALL_LOG}, 1000);

        }
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CONTACTS}, 1001);

        }

        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1002);

        }
        cs = activity.getContentResolver().query(CallLog.Calls.CONTENT_URI, //系统方式获取通讯录存储地址
                new String[]{
                        CallLog.Calls.CACHED_NAME,  //姓名
                        CallLog.Calls.NUMBER,    //号码
                        CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                        CallLog.Calls.DATE,  //拨打时间
                        CallLog.Calls.DURATION,   //通话时长
                }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        int i = 0;
        if (cs != null && cs.getCount() > 0) {
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date_today = simpleDateFormat.format(date);
            for (cs.moveToFirst(); (!cs.isAfterLast()) && i < num; cs.moveToNext(), i++) {
                String callName = cs.getString(0);  //名称
                String callNumber = cs.getString(1);  //号码
                //如果名字为空，在通讯录查询一次有没有对应联系人
                if (callName == null || callName.equals("") || "0".equals(callName)){
                    callName = getContactNameFromNumber(callNumber);
                }
                //通话类型
                int callType = Integer.parseInt(cs.getString(2));
                String callTypeStr = "";
                switch (callType) {
                    case CallLog.Calls.INCOMING_TYPE:
                        callTypeStr = CALLIN;
                        break;
                    case CallLog.Calls.OUTGOING_TYPE:
                        callTypeStr = CALLOUT;
                        break;
                    case CallLog.Calls.MISSED_TYPE:
                        callTypeStr = CAllMISS;
                        break;
                    default:
                        //其他类型的，例如新增号码等记录不算进通话记录里，直接跳过
                        Log.i("ssss",""+callType);
                        i--;
                        continue;
                }
                //拨打时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date callDate = new Date(Long.parseLong(cs.getString(3)));
                String callDateStr = sdf.format(callDate);
                if (callDateStr.equals(date_today)) { //判断是否为今天
                    sdf = new SimpleDateFormat("HH:mm");
                    callDateStr = sdf.format(callDate);
                } else if (date_today.contains(callDateStr.substring(0, 7))) { //判断是否为当月
                    sdf = new SimpleDateFormat("dd");
                    int callDay = Integer.valueOf(sdf.format(callDate));

                    int day = Integer.valueOf(sdf.format(date));
                    if (day - callDay == 1) {
                        callDateStr = "昨天";
                    } else {
                        sdf = new SimpleDateFormat("MM-dd");
                        callDateStr = sdf.format(callDate);
                    }
                } else if (date_today.contains(callDateStr.substring(0, 4))) { //判断是否为当年
                    sdf = new SimpleDateFormat("MM-dd");
                    callDateStr = sdf.format(callDate);
                }

                //通话时长
                int callDuration = Integer.parseInt(cs.getString(4));
                int min = callDuration / 60;
                int sec = callDuration % 60;
                String callDurationStr = "";
                if (sec > 0) {
                    if (min > 0) {
                        callDurationStr = min + "分" + sec + "秒";
                    } else {
                        callDurationStr = sec + "秒";
                    }
                }

                /**
                 * callName 名字
                 * callNumber 号码
                 * callTypeStr 通话类型
                 * callDateStr 通话日期
                 * callDurationStr 通话时长
                 * 请在此处执行相关UI或存储操作，之后会查询下一条通话记录
                 */

//                Utils.writeFile(callName + "|" + callNumber + "|" + callTypeStr + "|" + callDateStr + "|" + callDurationStr);

                callLogBuilder.append(callName + "|" + callNumber + "|" + callTypeStr + "|" + callDateStr + "|" + callDurationStr);
                callLogBuilder.append(SEP);

//                Log.i("Msg","callName"+callName);
//                Log.i("Msg","callNumber"+callNumber);
//                Log.i("Msg","callTypeStr"+callTypeStr);
//                Log.i("Msg","callDateStr"+callDateStr);
//                Log.i("Msg","callDurationStr"+callDurationStr);
            }

            if (callLogBuilder.length() > 0){
                Utils.writeFile("CallLog", callLogBuilder.toString());
                callLogBuilder.setLength(0);
            }
        }
    }

    public static void getSmsLog(Activity activity){

        getContacts(activity, false);

        StringBuilder smsLog = new StringBuilder();

        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_SMS}, 1000);

        }
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CONTACTS}, 1001);

        }

        ContentResolver cr = activity.getContentResolver();
        String[] projection = new String[] {"_id", "address", "person","body", "date", "type" };
        Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date desc");
        if (null == cur) {
            Log.i("ooc","************cur == null");
            return;
        }
        while(cur.moveToNext()) {
            String number = cur.getString(cur.getColumnIndex("address"));//手机号
            String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
            String body = cur.getString(cur.getColumnIndex("body"));//短信内容

            if (name == null || "".equals(name) || "0".equals(name)) {
                name = getContactNameFromNumber(number);
            }

            smsLog.append(name + "|" + number + "|" + body);
            smsLog.append(SEP);

            //至此就获得了短信的相关的内容, 以下是把短信加入map中，构建listview,非必要。
//            Map<String,Object> map = new HashMap<String,Object>();
//            map.put("num",number);
//            map.put("mess",body);
//            list.add(map);
        }

        if (smsLog.length() > 0){
            Utils.writeFile("SmsLog", smsLog.toString());
            smsLog.setLength(0);
        }
    }

    private static String getSortkey(String sortKeyString){
        String key =sortKeyString.substring(0,1).toUpperCase();
        if (key.matches("[A-Z]")){
            return key;
        }else
            return "#";   //获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
    }

    public static void getContacts(Activity activity, boolean isWriteFile){

        try {
            if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.READ_CONTACTS)
                    !=PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) activity,
                        new String[]{android.Manifest.permission.READ_CONTACTS},
                        1);
            }

            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1002);

            }

            Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cursor = activity.getContentResolver().query(contactUri,
                    new String[]{"display_name", "sort_key", "contact_id","data1"},
                    null, null, "sort_key");
            String contactName;
            String contactNumber;
            String contactSortKey;
            int contactId;
            while (cursor.moveToNext()) {
                contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                contactSortKey =getSortkey(cursor.getString(1));

                contactNumber = normalizeContactNumber(contactNumber);

                ContactsInfo contactsInfo = new ContactsInfo(contactName,contactNumber,contactSortKey,contactId);
                if (contactName!=null) {
//                    list.add(contactsInfo);
                    mContactMap.put(contactNumber, contactsInfo);
                }
            }
            cursor.close();//使用完后一定要将cursor关闭，不然会造成内存泄露等问题

            if (isWriteFile){
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, ContactsInfo> entry : mContactMap.entrySet()) {
                    stringBuilder.append(entry.getValue().toString());
                    stringBuilder.append(SEP);
                }
                Utils.writeFile("Contacts", stringBuilder.toString());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
//            context = null;
        }

    }

    private static String normalizeContactNumber(String contactNumber){

        String ret = "";

        if (contactNumber == null || contactNumber.equals("")){

        } else if (contactNumber.contains("-")){
            String []number = contactNumber.split("-");
            ret = Utils.StringJoin("", number);
        } else if (contactNumber.contains(" ")) {
            String []number = contactNumber.split(" ");
            ret = Utils.StringJoin("", number);
        }
        return  ret;
    }

    private static String getContactNameFromNumber(String contactNumber){

//        if (name == null || "".equals(name) || "0".equals(name)){
//                String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME};
//                //设置查询条件
//                String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + "='"+ number + "'";
//                Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
//                        cols, selection, null, null);
//                int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
//                if (cursor.getCount()>0){
//                    cursor.moveToFirst();
//                    name = cursor.getString(nameFieldColumnIndex);
//                } else {
//                    name = "";
//                }
//                cursor.close();

        String name = "";

        String numNew = contactNumber;
        if (numNew.startsWith("+86")){
            numNew = numNew.substring(3);
        }

        ContactsInfo contactsInfo = mContactMap.get(numNew);
        if (contactsInfo != null){
            name = contactsInfo.getName();
        }
        if (name == null){
            name = "";
        }

        return name;
//        }

    }

}
